package net.tngou.tpage.dao;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;

import net.tngou.tpage.jdbc.QueryHelper;
import net.tngou.tpage.pojo.Template;
import net.tngou.tpage.util.StringUtil;

/**
 * 模板
 * @author tngou@tngou.net
 *
 */
public class TemplateDao extends BaseDao {

	/**
	 * 取得模板
	 * @param page
	 * @param size
	 * @param user
	 * @param tags
	 * @param keyword
	 * @return
	 */
	public List<Template> list(int page,int size,long user,int [] tags,String keyword) {
		String tag="";
		for (int i : tags) {
			tag=tag+i+",";
		}
		Object[] params={user};
		tag=tag.substring(0,tag.length()-1);
		String sql = "SELECT template.* FROM `tpage_template` template,(SELECT template FROM `tpage_tag_template` WHERE tag "
				+ "IN("+tag+"))"
				+ " tag WHERE template.id=tag.template AND template.user=?";
		if(StringUtil.isNotEmpty(keyword))
		{
			sql =sql+" AND (id=? OR name=? OR pinyin=?) ";
			params=ArrayUtils.addAll(params, keyword,keyword,keyword+"%");
	
		}
		sql =sql+" ORDER BY id DESC ";
		return QueryHelper.query_slice(Template.class, sql, page, size,  params);
	}
	
	
	/**
	 * 取得总数
	 * @param user
	 * @param tags
	 * @param keyword
	 * @return
	 */
	public int  total(long user,int [] tags,String keyword) {
		String tag="";
		for (int i : tags) {
			tag=tag+i+",";
		}
		Object[] params={user};
		tag=tag.substring(0,tag.length()-1);
		String sql = "SELECT template.* FROM `tpage_template` template,(SELECT template FROM `tpage_tag_template` WHERE tag "
				+ "IN("+tag+"))"
				+ " tag WHERE template.id=tag.template AND template.user=?";
		if(StringUtil.isNotEmpty(keyword))
		{
			sql =sql+" AND (id=? OR name=? OR pinyin=?) ";
			params=ArrayUtils.addAll(params, keyword,keyword,keyword+"%");
	
		}
		return (int) QueryHelper.stat(sql, params);
	}
	
	
	/**
	 * 取得标签
	 * @param user
	 * @return
	 */
	public List<Map<String, Object>> tags(long user) {		
		String sql = "SELECT tag.*,tc.ct FROM `tpage_tag` tag ,"
				+ "(SELECT tag,count(*) as ct FROM `tpage_tag_template` GROUP BY tag) tc WHERE tag.id=tc.tag AND tag.user=? ORDER BY ct DESC";
		return QueryHelper.query(sql, user);
	}
	
}
